package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import service.SetmealService;

import java.util.List;
/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealControllor {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;
    /**
     * 查询所有的套餐
     * @param
     * @return
     */
    @RequestMapping("/getSetmeal")
    public Result findAll(){

        List<Setmeal> resultList=null;

        try {

            String mobile_findAllSetmeal = jedisPool.getResource().get("mobile_findAllSetmeal");
            if (mobile_findAllSetmeal != null){
                //把字符串转换成list集合
                 resultList = JSON.parseArray(mobile_findAllSetmeal, Setmeal.class);

                System.out.println("从redis读取套餐");
            }else {

                resultList=setmealService.findAll();
                //把list集合换成json字符串并存取redis
                jedisPool.getResource().set("mobile_findAllSetmeal", JSON.toJSON(resultList).toString());
                System.out.println("从数据库读取套餐");


            }

            return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS,resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL,null);
        }
    }

//    在根据id查询套餐时，同时将此套餐包含的检查组都查询出来，并且将检查组包含的检查项都查询出来
    @RequestMapping("/findById")
    public Result findById(int id){
        Setmeal setmeal= null ;
        try {
            String mobile_findByIdSetmeal = jedisPool.getResource().get("mobile_findByIdSetmeal"+id);
            if (mobile_findByIdSetmeal !=null){
                //把字符串转换成对象
                setmeal = JSON.parseObject(mobile_findByIdSetmeal, Setmeal.class);

                System.out.println("从redis读取套餐详细信息,根据套餐id");
            }else {
                setmeal= setmealService.findById(id);
                //把对象转换成对象字符串
                jedisPool.getResource().set("mobile_findByIdSetmeal"+id, JSON.toJSONString(setmeal));
                System.out.println("从数据库读取详细信息,根据套餐id");
            }

            return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS,setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL,null);
        }
    }





}
